<template>
    <div ref="chartContainer" :style="{ width: width, height: height }"></div>
</template>

<script>
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue';
import * as echarts from 'echarts';

export default {
    name: 'StepChart',
    props: {
        // 图表数据
        chartData: {
            type: Object,
            default: () => ({
                xAxisData: [],
                series: []
            })
        },
        // 标题
        title: {
            type: String,
            default: ''
        },
        // 图表宽度
        width: {
            type: String,
            default: '100%'
        },
        // 图表高度
        height: {
            type: String,
            default: '400px'
        },
        // 是否显示工具箱
        showToolbox: {
            type: Boolean,
            default: true
        },
        // 图例位置
        legendPosition: {
            type: String,
            default: 'top' // 可选：'top', 'bottom', 'left', 'right'
        }
    },
    emits: ['pointClick'],
    setup(props, { emit }) {
        const chartContainer = ref(null);
        let chartInstance = null;

        // 初始化图表
        const initChart = () => {
            if (!chartContainer.value) return;

            // 确保DOM已经渲染并且有尺寸
            if (chartInstance) {
                chartInstance.dispose();
                chartInstance = null;
            }

            // 延迟初始化，确保DOM已渲染
            nextTick(() => {
                // 再次检查DOM元素是否存在
                if (!chartContainer.value) return;

                try {
                    chartInstance = echarts.init(chartContainer.value);

                    // 注册点击事件
                    chartInstance.on('click', function (params) {
                        emit('pointClick', params);
                    });

                    updateChart();
                } catch (error) {
                    console.error('初始化图表失败:', error);
                }
            });
        };

        // 更新图表配置和数据
        const updateChart = () => {
            if (!chartInstance) return;

            try {
                // 准备图例数据
                const legendData = props.chartData.series.map(item => item.name);
                // 生成图表配置
                const option = {
                    title: {
                        text: props.title
                    },
                    tooltip: {
                        trigger: 'axis'
                    },
                    legend: {
                        data: legendData,
                        orient: ['left', 'right'].includes(props.legendPosition) ? 'vertical' : 'horizontal',
                        left: props.legendPosition === 'left' ? 'left' : 'center',
                        top: props.legendPosition === 'top' ? 'top' : 'auto',
                        bottom: props.legendPosition === 'bottom' ? 'bottom' : 'auto',
                        right: props.legendPosition === 'right' ? 'right' : 'auto'
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true
                    },
                    toolbox: {
                        show: props.showToolbox,
                        feature: {
                            saveAsImage: {}
                        }
                    },
                    xAxis: {
                        type: 'category',
                        data: props.chartData.xAxisData || []
                    },
                    yAxis: {
                        type: 'value'
                    },
                    series: props.chartData.series || []
                };

                // 设置图表配置
                chartInstance.setOption(option, true);
            } catch (error) {
                console.error('更新图表失败:', error);
            }
        };

        // 响应窗口大小变化
        const handleResize = () => {
            if (chartInstance) {
                try {
                    chartInstance.resize();
                } catch (error) {
                    console.error('调整图表大小失败:', error);
                }
            }
        };

        // 监听属性变化
        watch(() => props.chartData, () => {
            nextTick(() => {
                if (chartInstance) {
                    updateChart();
                } else {
                    initChart();
                }
            });
        }, { deep: true });

        watch(() => [props.title, props.showToolbox, props.legendPosition], () => {
            nextTick(() => {
                if (chartInstance) {
                    updateChart();
                }
            });
        });

        // 监听容器尺寸变化
        watch(() => [props.width, props.height], () => {
            nextTick(() => {
                if (chartInstance) {
                    handleResize();
                }
            });
        });

        // 组件挂载时初始化图表
        onMounted(() => {
            // 延迟初始化，确保DOM已完全渲染
            setTimeout(() => {
                initChart();
                window.addEventListener('resize', handleResize);
            }, 100);
        });

        // 组件卸载时销毁图表
        onUnmounted(() => {
            window.removeEventListener('resize', handleResize);
            if (chartInstance) {
                chartInstance.dispose();
                chartInstance = null;
            }
        });

        return {
            chartContainer
        };
    }
};
</script>